package cn.sc.summer.core.annotation;

import cn.hutool.core.text.CharSequenceUtil;
import lombok.extern.slf4j.Slf4j;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;

/**
 * 字段长度校验类注解，仅用于String类型字段
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {LengthValid.LengthValidAspect.class})
@Documented
public @interface LengthValid {

    /**
     * 校验错误信息
     */
    String message() default "文本长度不符合要求！";

    /**
     * 校验分组信息
     */
    Class<?>[] groups() default {};

    /**
     * 载荷
     */
    Class<? extends Payload>[] payload() default {};

    /**
     * 字符串最小长度
     */
    int min() default 0;

    /**
     * 字符串最大长度
     */
    int max() default 0;

    /**
     * 类名：字符串长度校验逻辑
     *
     * @author a-xin
     * @date 2024/5/7 13:15
     */
    @Slf4j
    class LengthValidAspect implements ConstraintValidator<LengthValid, String> {

        private int min;

        private int max;

        @Override
        public void initialize(LengthValid constraintAnnotation) {
            min = constraintAnnotation.min();
            max = constraintAnnotation.max();
        }

        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {
            if (CharSequenceUtil.isBlank(value)) {
                return Boolean.TRUE;
            }
            int length = value.length();
            return length >= min && length <= max;
        }
    }

}
